package com.trainoo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.trainoo.repository.ChapterRepository;
import com.trainoo.response.NovelResponse;
import com.trainoo.domain.Chapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

/**
 * Created by zhoutao on 2018/7/3 14:48
 */
@RestController()
@RequestMapping("/novel")
public class NovelController {

    private static Logger LOG = LoggerFactory.getLogger(NovelController.class);

    @Autowired
    private ChapterRepository repository;

    /**
     * 使用 Sort sort = new Sort(Sort.Direction.DESC, "title_num"); 报错如下：
     *  org.springframework.data.mapping.PropertyReferenceException:
     *  No property num found for type String! Traversed path: Chapter.title.
     *
     *  终究的原因是spring-data-commons版本低导致的，升级到新版本就没问题了
     *  或者在查询时添加的Sort中的Orderby参数 不带下划线就可以了
     *
     */
    @GetMapping(value = "chapters")
    public NovelResponse getChapters(@RequestParam("page") int page, @RequestParam("size") int size){
        NovelResponse resObj = new NovelResponse();
        try {
            Sort sort = new Sort(Sort.Direction.ASC, "titleNum"); // 根据titleNum升序排列
            Pageable pageable = new PageRequest(page, size, sort);// 每页size条数据，第page+1页(PageRequest是从0开始计数的)
            Page<Chapter> chapters = repository.findAll(pageable);
            resObj.setCode("0000");
            resObj.setMsg("查询成功！");
            resObj.setData(chapters);
            return resObj;
        } catch (Exception e) {
            resObj.setCode("9999");
            resObj.setMsg("查询失败！");
            LOG.error("查询章节信息出现异常：{}", e);
        }
        return resObj;
    }

    /**
     *  RequestParam | PathVariable 的区别：
     *
     *  使用 getChapterByNum(@RequestParam("num") int num)
     *  从 request 里面获取参数，eg： http://url/chapter?num=1
     *
     *  使用 getChapterByNum(@PathVariable("num") int num)
     *  从 url 模板里面获取参数，eg： http://url/chapter/1
     *
     */
    @GetMapping(value = "chapter/{num}")
    public NovelResponse getChapterByNum(@PathVariable("num") int num) throws JsonProcessingException {
        NovelResponse resObj = new NovelResponse();
        try{
            Chapter chapter = repository.findByNum(num);
            resObj.setCode("0000");
            resObj.setMsg("查询成功！");
            resObj.setData(chapter);
            return resObj;
        } catch (Exception e){
            resObj.setCode("9999");
            resObj.setMsg("查询失败！");
            LOG.error("查询章节信息出现异常：{}", e);
        }
        return resObj;
    }
}
